package com.night.icm.controller.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.night.icm.common.jwt.JwtTokenUtil;
import com.night.icm.persistence.core.entity.JwtUser;
import com.night.icm.persistence.core.entity.LoginUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * JwtAuthenticationFilter
 * 鉴权过滤器
 *
 * @author Liao ZhiYong
 * @date 2019/12/6
 */
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private ThreadLocal<Integer> rememberMe = new ThreadLocal<>();
    private AuthenticationManager authenticationManager;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl("/auth/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        // 从输入流中获取到登录的信息
        try {
            LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
            rememberMe.set(loginUser.getRememberMe());
//            UserDTO user = userService.findByName(JwtTokenUtil.getUsername(loginUser.getUsername()));
//            if (user != null && SecurityContextHolder.getContext().getAuthentication() == null){
//                Set<String> roles = new HashSet<>();
//                roles.add(user.getRole());
//                Collection<SimpleGrantedAuthority> authorities = roles
//                        .stream()
//                        .map(SimpleGrantedAuthority::new)
//                        .collect(Collectors.toSet());
//                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                        user, null, authorities);
//                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
//                        request));
//                SecurityContextHolder.getContext().setAuthentication(authentication);
//                return authenticationManager.authenticate(
//                        new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), authorities)
//                );
//            } else {
//                return authenticationManager.authenticate(
//                        new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>())
//                );
//            }
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 成功验证后调用的方法
     * 如果验证成功，就生成token并返回
     *
     * @param request    请求
     * @param response   响应
     * @param chain      chain过滤器
     * @param authResult 权限
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) {

        JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
        logger.info("jwtUser:" + jwtUser.toString());
        boolean isRemember = rememberMe.get() == 1;

        String role = "";
        Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }

        String token = JwtTokenUtil.createToken(jwtUser.getUsername(), role, isRemember);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        response.setHeader("Authorization", JwtTokenUtil.TOKEN_PREFIX + token);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                jwtUser, null, authorities);
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        rememberMe.remove();
    }

    /**
     * 鉴权失败
     *
     * @param request  请求
     * @param response 响应
     * @param failed   权限异常
     * @throws IOException 异常
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
        response.getWriter().write("authentication failed, reason: " + failed.getMessage());
    }
}